<template>
  <div class="directoryTree">
    <div class="top">
      <span class="title" @click="allDirectory">{{title}}</span>
      <template v-if="isKnowledge">
        <span v-functions="['knowledge_mgt_channel_1_add_root_directory']" v-if="isShowActionBtn && limitObj.add" class="V7_iconfont V7_iconV7tubiao_tianjia" @click="add($event)"></span>
        <span v-functions="['knowledge_mgt_channel_1_import']" class="V7_iconfont V7_iconV7tubiao_piliangdaoru" @click="importDialog"></span>
      </template>
      <span v-if="isShowActionBtn && limitObj.add && !isKnowledge" class="V7_iconfont V7_iconV7tubiao_tianjia" @click="add($event)"></span>
    </div>
    <el-tree
      :highlight-current="isShowHighlight"
      :data="treeData"
      node-key="_id"
      :expand-on-click-node="false"
      :default-expand-all="true"
      :show-checkbox="false"
      @node-click="nodeClick">
      <span :class="['custom-tree-node','clearfix', data.disabled && 'disabled']" slot-scope="{ node, data }">
        <span class="content"
          :style="{ maxWidth: node.level === 4 ? 'calc(100% - 40px)' : 'calc(100% - 55px)'}">
          {{ node.label }}
        </span>
        <span class="btn fr" v-if="isShowActionBtn && data.canEdit">
          <i class="V7_iconfont V7_iconV7tubiao_tianjia" @click="add($event, data)" v-if="node.level < treeLevel && limitObj.add"></i>
          <i class="V7_iconfont V7_iconV7tubiao_xianbianji" @click="edit($event, data)" v-if="limitObj.edit"></i>
          <i class="el-icon-delete" @click="del($event, data)" v-if="limitObj.del"></i>
        </span>
      </span>
    </el-tree>
     <el-dialog
      title="导入知识库"
      :visible.sync="importVisible"
      width="30%">
      <div>
        <el-button size="mini" icon="el-icon-download" class="fl importBtn">
          <a href="/temp/km-Import.xlsx" download="km-import">下载导入模板</a>
        </el-button>
        <el-upload
          class="upload-demo"
          ref="epxortKm"
          accept=".xls, .xlsx"
          :action="kmUrl"
          :limit='1'
          :on-success="handleImportSuccess"
          :on-remove="handleRemove"
          :headers="{
            sessionid: accountObj.userId,
            loginToken: accountObj.loginToken
          }">
          <el-button size="mini" class="fl" style="marginLeft: 10px">导入Excel文件</el-button>
        </el-upload>
        <div class="instructions">
          <h5>说明：</h5>
          <ul>
            <li>1、支持后缀为xls何xlsx的excel文件导入；</li>
            <li>2、wps格式的文件导入成功率高，office低版本容易导入失败；</li>
            <li>3、支持一个文件一个工作表，多个工作表无法导入；</li>
            <li>4、单次最多导入1000条，超出1000条无法导入；</li>
            <li>5、模板表头不可修改，修改后无法导入；</li>
            <li>6、导入文件不可超出**M，超出后无法导入；</li>
            <li>7、导入时异步处理，提交导入后可以立刻进行其他的导入，服务器会排队处理，结果在【传输中心】查看；</li>
          </ul>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importVisible = false">取 消</el-button>
        <el-button type="primary" @click="importSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { KmModule } from '@/store/modules/km'
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import { knowledgeAccess } from '@/utils/kmAccess'
@Component({
  name: 'directoryTree'
})
export default class DirectoryTree extends Vue {
[x: string]: any
  @Prop() private treeData: any
  @Prop(({ default: () => true })) private isKnowledge?: boolean
  @Prop({ default: () => '目录' }) private title: string | undefined
  @Prop({ default: () => true }) private isShowActionBtn?: boolean | undefined
  @Prop({ default: () => 4 }) private treeLevel: any
  @Prop({
    default: () => {
      return { add: true, edit: true, del: true }
    }
  }) private limitObj: any

  private currentNodeObj = {}

  private isShowHighlight = true

  private importVisible = false

  private fileObj = {
    path: '',
    count: ''
  }

  private accountObj = {
    account: '',
    userId: '',
    loginToken: ''
  }

  get kmUrl () {
    console.log(this.accountObj.account)
    return '/upload?accountId=' + this.accountObj.account + '&module=km'
  }

  private handleImportSuccess (res: any) {
    if (res && res.success) {
      this.fileObj.path = res.data.path
    }
  }

  private handleRemove () {
    this.fileObj.path = ''
  }

  private importSave () {
    if (!this.fileObj.path) {
      this.$message.error('请选择文件上传')
      return
    }
    const actionData = {
      url: '/im-km/import/action/importTask',
      method: 'post',
      data: {
        kmType: 'inner',
        filepath: this.fileObj.path
      }
    }
    const epxortRef: any = this.$refs.epxortKm
    epxortRef.clearFiles()
    KmModule.KmCommonAction(actionData).then(res => {
      if (res && res.success) {
        this.$message.success('导入任务已经生成，请前往传输中心查看！')
        this.importVisible = false
      }
    })
  }

  @Watch('treeData', { immediate: true })
  private setTreeData (tree) {
    this.deepSetAccess(tree || [])
  }

  private checkHasAccess (data) {
    return knowledgeAccess(data, this.$store.state.common.session)
  }

  private deepSetAccess (list) {
    const each = (arr) => {
      arr.forEach(i => {
        const { canEdit, canShow } = this.checkHasAccess(i)
        this.$set(i, 'canEdit', canEdit);
        this.$set(i, 'canShow', canShow);
        this.$set(i, 'disabled', !canShow && !canEdit);
        if (i.children?.length > 0) {
          each(i.children)
        }
      })
    }
    each(list)
  }

  private importDialog () {
    this.importVisible = true
  }

  private add ($event: any, row?: any) { // 添加目录 没有row代表1级目录添加
    $event.stopPropagation()
    if (row) {
      row.level++
    }
    this.$emit('addDirTree', row || { level: 1 })
  }

  private edit ($event: any, row: any) { // 修改目录
    $event.stopPropagation()
    this.$emit('editDirTree', row || {})
  }

  private del ($event: any, row: any) { // 删除目录
    $event.stopPropagation()
    this.$emit('delDirTree', row || {})
  }

  private nodeClick (node: any, data: any) {
    if (data.disabled) {
      return
    }
    this.currentNodeObj = { node, data }
    KmModule.setClickNode(this.currentNodeObj)
    this.isShowHighlight = true
    this.$emit('nodeClick', this.currentNodeObj)
  }

  private allDirectory () {
    if (this.treeLevel > 2) {
      return
    }
    this.isShowHighlight = false
    this.$emit('allDirectory')
  }

  private beforeMount () {
    this.accountObj.account = (this.$store as any).state.common.session.account._id
    this.accountObj.userId = (this.$store as any).state.common.session.user._id
    this.accountObj.loginToken = (this.$store as any).state.common.session.user.loginToken
  }
}
</script>
<style lang="stylus" scoped>
  .directoryTree
    margin-top 10px
    .top
      font-size 14px
      margin-bottom 10px
      .title
        cursor pointer
      .V7_iconfont
        font-size 13px
        margin-left 10px
        cursor pointer
        color #B3B9C7
      .V7_iconfont:hover
        color #008BEE
    .btn
      // margin-left 20px
      display none
      i
        cursor pointer
        color #B3B9C7
        font-size 12px
        margin 0px 2px
      i:hover
        color #008BEE
    .custom-tree-node
      width calc(100% - 24px)
      .content
        // max-width calc(100% - 65px)
        display inline-block
        text-overflow ellipsis
        overflow hidden
        white-space nowrap
</style>
<style lang="stylus">
  .directoryTree
    .el-tree
      font-size 14px
    .el-tree-node__content
      margin 5px 0px
    .el-tree-node__content:hover .btn
      display inline
    .el-tree__empty-block
      min-height 360px
  .disabled
    cursor not-allowed
  .importBtn
    a
      color #303753
  .importBtn:hover a
    color #008cee
  .instructions
    margin-top 22px
    h5
      font-size 12
    li
      padding 4px
      color #767E91
      font-size 12px
</style>
